//
//  AHAHViewController.m
//  Telemedicine
//
//  Created by Trong Ton on 5/20/14.
//  Copyright (c) 2014 Trong Ton. All rights reserved.
//

#import "AHAHViewController.h"
#import "JSON.h"
#import "PartnerViewCell.h"

@interface AHAHViewController ()

@end

@implementation AHAHViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    isLoadPartnerList = YES;
    
    NSArray *vComp = [[UIDevice currentDevice].systemVersion componentsSeparatedByString:@"."];
    int startYView = ([[vComp objectAtIndex:0] intValue] >= 7)?20:0;
    
    UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, startYView, self.view.bounds.size.width, self.view.bounds.size.height - 49 -startYView)];
    //    contentView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"home_bottom.jpg"]];
    [self.view addSubview:contentView];
    [contentView release];
    
    UIImageView *bigImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, contentView.bounds.size.width, 218)];
    [bigImage setImage:[UIImage imageNamed:@"bg_partner.jpg"]];
    [contentView addSubview:bigImage];
    [bigImage release];
    
    UIView *spaceLine = [[UIView alloc] initWithFrame:CGRectMake(0, 218-2, contentView.bounds.size.width, 2)];
    spaceLine.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"home_bottom.jpg"]];
    [bigImage addSubview:spaceLine];
    [spaceLine release];
    
    UIView *leftSpaceLine = [[UIView alloc] initWithFrame:CGRectMake(0, 218-8, 59, 8)];
    leftSpaceLine.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"home_bottom.jpg"]];
    [bigImage addSubview:leftSpaceLine];
    [leftSpaceLine release];
    
    partnerTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 218, contentView.bounds.size.width, contentView.bounds.size.height - 218 - 23)];
    partnerTableView.delegate = self;
    partnerTableView.dataSource = self;
    [partnerTableView setSeparatorColor:[UIColor whiteColor]];
    [contentView addSubview:partnerTableView];
    [partnerTableView release];
    
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"6.0")) {
        UIRefreshControl *refreshAdd = [[[UIRefreshControl alloc] init] autorelease];
        [refreshAdd addTarget:self action:@selector(dropViewDidBeginRefreshing:) forControlEvents:UIControlEventValueChanged];
        [partnerTableView addSubview:refreshAdd];
    }
    else{
        refreshControl = [[ODRefreshControl alloc] initInScrollView:partnerTableView];
        [refreshControl addTarget:self action:@selector(dropViewDidBeginRefreshing:) forControlEvents:UIControlEventValueChanged];
    }
    
    UIView *loadingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
    UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    activityView.center = CGPointMake(loadingView.bounds.size.width/2, loadingView.bounds.size.height/2);
    [activityView startAnimating];
    [loadingView addSubview:activityView];
    [activityView release];
    [partnerTableView setTableHeaderView:loadingView];
    [loadingView release];
    
    UIImageView *phoneInfo = [[UIImageView alloc] initWithFrame:CGRectMake(0, contentView.bounds.size.height - 23, contentView.bounds.size.width, 23)];
    [phoneInfo setImage:[UIImage imageNamed:@"home_bottomwebsite_url.jpg"]];
    [contentView addSubview:phoneInfo];
    [phoneInfo release];
    
    [self getAllPartnerCategory];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (errorLoadList == YES) {
        [self getAllPartnerCategory];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    if (categoryPartnerArray) {
        [categoryPartnerArray release];
    }
    if (partnersDic) {
        [partnersDic release];
    }
    [super dealloc];
}

- (void)showPartnerView {
    if(partnerView == nil) {
        NSArray *vComp = [[UIDevice currentDevice].systemVersion componentsSeparatedByString:@"."];
        int startYView = ([[vComp objectAtIndex:0] intValue] >= 7)?20:0;
        partnerView = [[UIView alloc] initWithFrame:CGRectMake(0, startYView, self.view.bounds.size.width, self.view.bounds.size.height - startYView)];
        partnerView.backgroundColor = [UIColor whiteColor];
        
        listPartner = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, partnerView.bounds.size.width, partnerView.bounds.size.height - 38)];
        listPartner.delegate = self;
        listPartner.dataSource = self;
        [listPartner setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        [partnerView addSubview:listPartner];
        [listPartner release];
        
        if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"6.0")) {
            UIRefreshControl *refreshAdd = [[[UIRefreshControl alloc] init] autorelease];
            [refreshAdd addTarget:self action:@selector(dropPartnerDidBeginRefreshing:) forControlEvents:UIControlEventValueChanged];
            [listPartner addSubview:refreshAdd];
        }
        else{
            refreshPartner = [[ODRefreshControl alloc] initInScrollView:listPartner];
            [refreshPartner addTarget:self action:@selector(dropPartnerDidBeginRefreshing:) forControlEvents:UIControlEventValueChanged];
        }
        
        
        UIButton *closeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        closeButton.frame = CGRectMake(2, listPartner.bounds.size.height, listPartner.bounds.size.width - 4, 36);
        closeButton.backgroundColor = [UIColor lightGrayColor];
        [closeButton setTitle:@"OK" forState:UIControlStateNormal];
        [closeButton addTarget:self action:@selector(closeButtonPress:) forControlEvents:UIControlEventTouchUpInside];
        [partnerView addSubview:closeButton];
        
        [self.view addSubview:partnerView];
        [partnerView release];
    }
}

- (void)closeButtonPress:(id)sender {
    [partnerView removeFromSuperview];
    partnerView = nil;
}

- (void)dropViewDidBeginRefreshing:(ODRefreshControl *)refreshControl
{
    if([AppDelegate sharedDelegate].isNetworkAvailable) {
        _reloading = YES;
        [self getAllPartnerCategory];
    }
    else {
        _reloading = YES;
        [self doneLoadingTableViewData];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"No internet connections, please check your settings." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alertView show];
        [alertView release];
    }
}

- (void)dropPartnerDidBeginRefreshing:(ODRefreshControl *)refreshControl {
    if([AppDelegate sharedDelegate].isNetworkAvailable) {
        _reloading = YES;
        [self getAllPartnerWithID:idCategorySelect];
    }
    else {
        _reloading = YES;
        [self doneLoadingTablePartnerData];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"No internet connections, please check your settings." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alertView show];
        [alertView release];
    }
}

- (void)doneLoadingTableViewData {
	
	//  model should call this when its done loading
    if (_reloading) {
        double delayInSeconds = 0.2;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"6.0")) {
                //[mediaTableView.refreshControl endRefreshing];
                for (UIView *view in partnerTableView.subviews) {
                    if([view isKindOfClass:[UIRefreshControl class]]) {
                        UIRefreshControl *refresh = (UIRefreshControl*)view;
                        [refresh endRefreshing];
                    }
                }
            }
            else {
                [refreshControl endRefreshing];
            }
        });
    }
    [partnerTableView reloadData];
    _reloading = NO;
}

- (void)doneLoadingTablePartnerData {
    if (_reloading && partnerView) {
        double delayInSeconds = 0.2;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"6.0")) {
                //[mediaTableView.refreshControl endRefreshing];
                for (UIView *view in listPartner.subviews) {
                    if([view isKindOfClass:[UIRefreshControl class]]) {
                        UIRefreshControl *refresh = (UIRefreshControl*)view;
                        [refresh endRefreshing];
                    }
                }
            }
            else {
                [refreshPartner endRefreshing];
            }
        });
        [listPartner reloadData];
    }
    _reloading = NO;
}

- (void)getAllPartnerCategory {
    //https://wp-dot-erudite-stratum-347.appspot.com/partner_category_controller/getall/
    
    APIsBaseService *serVice = [APIsBaseService service];
    
//    NSMutableDictionary *dictionData = [NSMutableDictionary dictionary];
//    
//    
//    SBJsonWriter *jsonWriter = [[[SBJsonWriter alloc] init]autorelease];
//    
//    NSMutableDictionary *dictionary  = [NSMutableDictionary dictionary];
//    [dictionary setObject:[jsonWriter stringWithObject:dictionData] forKey:@"requestdata"];
    
    [serVice requestWithURL:kGetAllPartnerCategory
                     params:nil
               successBlock:^(NSDictionary *dictionary){
                   NSArray *arrays = [dictionary objectForKey:@"docs"];
                   if(arrays && [arrays count] > 0) {
                       [self saveCategoryPartnerToCache:arrays];
                       if (categoryPartnerArray) {
                           [categoryPartnerArray release];
                           categoryPartnerArray = nil;
                       }
                       categoryPartnerArray = [[NSMutableArray alloc] initWithArray:arrays];
                       partnerTableView.tableHeaderView = nil;
                       [partnerTableView reloadData];
                   }
                   else {
                       categoryPartnerArray = [self loadCategoryPartnerFromCache];
                       if (categoryPartnerArray == nil) {
                           errorLoadList = YES;
                           UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert !" message:@"There is an error when application is trying to get partners list. Please try again later." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                           [alertView show];
                           [alertView release];
                       }
                       else {
                           partnerTableView.tableHeaderView = nil;
                           [partnerTableView reloadData];
                       }
                   }
                   [self performSelectorOnMainThread:@selector(doneLoadingTableViewData) withObject:nil waitUntilDone:YES];
               }
                 errorBlock:^(NSError *error){
                     categoryPartnerArray = [self loadCategoryPartnerFromCache];
                     if (categoryPartnerArray == nil) {
                         errorLoadList = YES;
                         NSDictionary *userInfo = [error userInfo];
                         NSString *errorString = [userInfo objectForKey:@"NSLocalizedDescription"];
                         UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert !" message:errorString delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                         [alert show];
                         [alert release];
                     }
                     else {
                         partnerTableView.tableHeaderView = nil;
                         [partnerTableView reloadData];
                     }
                     [self performSelectorOnMainThread:@selector(doneLoadingTableViewData) withObject:nil waitUntilDone:YES];
                 }
                 httpMethod:@"GET"];
}

- (void)getAllPartnerWithID:(int)idCategory {
    //https://wp-dot-erudite-stratum-347.appspot.com/partner_controller/getall
    APIsBaseService *serVice = [APIsBaseService service];
    [serVice requestWithURL:kGetAllPartner
                     params:nil
               successBlock:^(NSDictionary *dictionary){
                   NSArray *arrays = [dictionary objectForKey:@"docs"];
                   NSMutableDictionary *partnerDic = [[[NSMutableDictionary alloc] init] autorelease];
                   if(arrays && [arrays count] > 0) {
                       for(int i = 0; i < [arrays count]; i++) {
                           NSDictionary *item = [arrays objectAtIndex:i];
                           NSNumber *idCategory = [NSNumber numberWithInt:[[item objectForKey:@"category_id"] intValue]];
                           if([partnerDic objectForKey:idCategory]) {
                               NSMutableArray *partners = [partnerDic objectForKey:idCategory];
                               [partners addObject:item];
                           }
                           else {
                               NSMutableArray *partners = [[[NSMutableArray alloc] init] autorelease];
                               [partners addObject:item];
                               [partnerDic setObject:partners forKey:idCategory];
                           }
                       }
                       [self savePartnersToCache:partnerDic];
                       if (partnersDic) {
                           [partnersDic release];
                           partnersDic = nil;
                       }
                       partnersDic = [[NSDictionary alloc] initWithDictionary:partnerDic];
                       partnerSelected = [partnerDic objectForKey:[NSNumber numberWithInt:idCategory]];
                       if(_reloading == NO) {
                           [self showPartnerView];
                       }
                       isLoadPartnerList = NO;
                   }
                   else {
                       partnersDic = [self loadPartnersFromCache];
                       if (partnersDic == nil) {
                           errorLoadList = YES;
                           UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert !" message:@"An unknown error has occurred. Please try again." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                           [alertView show];
                           [alertView release];
                       }
                       else {
                           partnerSelected = [partnersDic objectForKey:[NSNumber numberWithInt:idCategory]];
                           if(_reloading == NO) {
                               [self showPartnerView];
                           }
                       }
                   }
                   [self performSelectorOnMainThread:@selector(doneLoadingTablePartnerData) withObject:nil waitUntilDone:YES];
               }
                 errorBlock:^(NSError *error){
                     partnersDic = [self loadPartnersFromCache];
                     if (partnersDic == nil) {
                         errorLoadList = YES;
                         NSDictionary *userInfo = [error userInfo];
                         NSString *errorString =[userInfo objectForKey:@"NSLocalizedDescription"];
                         UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert !" message:errorString delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                         [alert show];
                         [alert release];
                     }
                     else {
                         partnerSelected = [partnersDic objectForKey:[NSNumber numberWithInt:idCategory]];
                         [self showPartnerView];
                     }
                     [self performSelectorOnMainThread:@selector(doneLoadingTablePartnerData) withObject:nil waitUntilDone:YES];
                 }
                 httpMethod:@"GET"];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == partnerTableView) {
        NSInteger number = categoryPartnerArray!=nil?[categoryPartnerArray count]:0;
        return number;
    }
    else {
        NSInteger number = partnerSelected!=nil?[partnerSelected count]:0;
        return number;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == partnerTableView) {
        static NSString *cellIdentifier = @"UIColectionTableViewCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] init] autorelease];
        }
        if (indexPath.row < [categoryPartnerArray count]) {
            int indexColor = indexPath.row%4;
            UIColor *colorSet;// = [UIColor colorWithRed:28.0/255.0 green:125.0/255.0 blue:155.0/255.0 alpha:1.0];
            if (indexColor == 0) {
                colorSet = [UIColor colorWithRed:28.0/255.0 green:125.0/255.0 blue:155.0/255.0 alpha:1.0];
            }
            else if (indexColor == 1){
                colorSet = [UIColor colorWithRed:167.0/255.0 green:201.0/255.0 blue:223.0/255.0 alpha:1.0];
            }
            else if (indexColor == 2){
                colorSet = [UIColor colorWithRed:51.0/255.0 green:181.0/255.0 blue:229.0/255.0 alpha:1.0];
            }
            else {
                colorSet = [UIColor colorWithRed:73.0/255.0 green:121.0/255.0 blue:141.0/255.0 alpha:1.0];
            }
            cell.contentView.backgroundColor = colorSet;
            NSDictionary *item = [categoryPartnerArray objectAtIndex:indexPath.row];
            NSString *titleCategory = [item objectForKey:@"name"];
            if (titleCategory && titleCategory.length >0)  {
                cell.textLabel.font = [UIFont systemFontOfSize:14];
                cell.textLabel.text = titleCategory;
            }
            else {
                cell.textLabel.text = @"";
            }
        }
        cell.selectionStyle = UITableViewCellSelectionStyleBlue;
        
        return  cell;
    }
    else {
        static NSString *cellIdentifier = @"UIPartnerTableViewCell";
        PartnerViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[[PartnerViewCell alloc] init] autorelease];
        }
        NSDictionary *item = [partnerSelected objectAtIndex:indexPath.row];
        [cell setupCellTableView:item];
        cell.selectionStyle = UITableViewCellSelectionStyleBlue;
        return  cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == partnerTableView) {
        return 55.0f;
    }else {
        return 84.0f;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
//    [[AppDelegate sharedDelegate]callGoogleHangoutWithEmail:@"phuong.huynhthai@gmail.com"];
//    return;
    if (tableView == partnerTableView) {
        idCategorySelect = [[[categoryPartnerArray objectAtIndex:indexPath.row] objectForKey:@"id"] intValue];
        if(isLoadPartnerList == YES || partnersDic == nil) {
            [self getAllPartnerWithID:idCategorySelect];
        }
        else {
            partnerSelected = nil;
            partnerSelected = [partnersDic objectForKey:[NSNumber numberWithInt:idCategorySelect]];
            [self showPartnerView];
        }
    }
    else {
        NSDictionary *item = [partnerSelected objectAtIndex:indexPath.row];
        NSString *skypePartner = [item objectForKey:@"skype_name"];
        if(skypePartner && skypePartner.length > 0) {
            [[AppDelegate sharedDelegate]callSkypeWithName:skypePartner];
        }
        else {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert !" message:@"An unknow error has occurred, there might be problems with the data format from our server. Please try again in few seconds." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alertView show];
            [alertView release];
        }
    }
}

- (NSMutableArray *)loadCategoryPartnerFromCache {
    NSMutableArray *dataReturn = nil;
    NSString *file = [kDocumentDirectory stringByAppendingPathComponent:kCategoryPartnerFromCache];
    if ([[NSFileManager defaultManager] fileExistsAtPath:file]) {
        dataReturn = [[NSMutableArray alloc]initWithContentsOfFile:file];//arrayWithContentsOfFile:file] copy];
    }
    return dataReturn;
}

- (void)saveCategoryPartnerToCache:(NSArray *)dataSave {
    if (dataSave && [dataSave count] > 0) {
        if (![dataSave writeToFile:[kDocumentDirectory stringByAppendingPathComponent:kCategoryPartnerFromCache] atomically:YES]) {
#if DEBUG
            //NSLog(@"%s, cannot save forms to cache",__PRETTY_FUNCTION__);
#endif
        }
    }
}

- (NSDictionary *)loadPartnersFromCache {
    NSDictionary *dataReturn = nil;
    NSString *file = [kDocumentDirectory stringByAppendingPathComponent:kPartnersFromCache];
    if ([[NSFileManager defaultManager] fileExistsAtPath:file]) {
        dataReturn = [[NSDictionary alloc]initWithContentsOfFile:file];//arrayWithContentsOfFile:file] copy];
    }
    return dataReturn;
}

- (void)savePartnersToCache:(NSDictionary *)dataSave {
    if (dataSave && [dataSave count] > 0) {
        if (![dataSave writeToFile:[kDocumentDirectory stringByAppendingPathComponent:kPartnersFromCache] atomically:YES]) {
#if DEBUG
            //NSLog(@"%s, cannot save forms to cache",__PRETTY_FUNCTION__);
#endif
        }
    }
}

@end
